package com.edais.actions;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

public class TestAndroidClient {

	static class HttpAssist  implements Serializable{
		private static final String TAG = "uploadFile";
		private static final int TIME_OUT = 10 * 10000000; // 超时时间
		private static final String CHARSET = "utf-8"; // 设置编码
		public static final String SUCCESS = "1";
		public static final String FAILURE = "0";

		/**
		 * android客户端
		 * 
		 * @param file
		 * @return
		 */
		public static String uploadFile(File file) {
			String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
			String PREFIX = "--";// 行开始
			String LINE_END = "\r\n";// 行结束
			String CONTENT_TYPE = "multipart/form-data"; // 内容类型
			// String RequestURL =
			// "http://192.168.0.100:7080/YkyPhoneService/Uploadfile1";
			// String RequestURL =
			// "http://127.0.0.1:8080/EDAIMobile/user/modifySculpture";
			String RequestURL = "http://127.0.0.1:8080/EDAIMobile/test/getTest";
			// ?localize=cn&versionCode=2.0&userId=2731804&fileName=head.jpg&fileContentType=jpg
			OutputStream outputSteam = null;
			DataOutputStream dos = null;
			try {
				URL url = new URL(RequestURL);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setReadTimeout(TIME_OUT); // 超时时间
				conn.setConnectTimeout(TIME_OUT); // 超时时间
				conn.setDoInput(true); // 允许输入流
				conn.setDoOutput(true); // 允许输出流
				conn.setUseCaches(false); // 不允许使用缓存
				conn.setRequestMethod("POST"); // 请求方式
				conn.setRequestProperty("Charset", CHARSET); // 设置编码
				conn.setRequestProperty("connection", "keep-alive");
				conn.setRequestProperty("Content-Type", CONTENT_TYPE
						+ ";boundary=" + BOUNDARY);// 内容类型
				
				if (file != null) {
					/**
					 * 当文件不为空，把文件包装并且上传
					 */
					outputSteam = conn.getOutputStream();
					dos = new DataOutputStream(outputSteam);
					StringBuffer sb = new StringBuffer();
					sb.append(PREFIX);
					sb.append(BOUNDARY);// 边界标识 随机生成
					sb.append(LINE_END);
					/**
					 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
					 * filename是文件的名字，包含后缀名的 比如:abc.png
					 */
					sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
							+ file.getName() + "\"" + LINE_END);
					sb.append("Content-Type: application/octet-stream; charset="
							+ CHARSET + LINE_END);
					sb.append(LINE_END);
					dos.write(sb.toString().getBytes());
					InputStream is = new FileInputStream(file);
					byte[] bytes = new byte[1024];
					int len = 0;
					while ((len = is.read(bytes)) != -1) {
						dos.write(bytes, 0, len);
					}
					is.close();
					dos.write(LINE_END.getBytes());
					byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
							.getBytes();
					dos.write(end_data);
					dos.flush();
					dos.close();
					outputSteam.close();
					/**
					 * 获取响应码 200=成功 当响应成功，获取响应的流
					 */
					int res = conn.getResponseCode();
					System.out.println(res);
					if (res == 200) {
						return SUCCESS;
					}
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (dos != null) {
					try {
						dos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (outputSteam != null) {
					try {
						outputSteam.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return FAILURE;
		}

		/**
		 * android客户端
		 * 
		 * @param file
		 * @return
		 */
		public static String uploadFile2(File file) {
			String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
			String PREFIX = "--";// 行开始
			String LINE_END = "\r\n";// 行结束
			String CONTENT_TYPE = "multipart/form-data"; // 内容类型
			// String RequestURL =
			// "http://192.168.0.100:7080/YkyPhoneService/Uploadfile1";
			// String RequestURL =
			// "http://127.0.0.1:8080/EDAIMobile/user/modifySculpture";
			String RequestURL = "http://127.0.0.1:8080/EDAIMobile/test/upload";
			// ?localize=cn&versionCode=2.0&userId=2731804&fileName=head.jpg&fileContentType=jpg
			OutputStream outputSteam = null;
			DataOutputStream dos = null;
			try {
				URL url = new URL(RequestURL);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setReadTimeout(TIME_OUT); // 超时时间
				conn.setConnectTimeout(TIME_OUT); // 超时时间
				conn.setDoInput(true); // 允许输入流
				conn.setDoOutput(true); // 允许输出流
				conn.setUseCaches(false); // 不允许使用缓存
				conn.setRequestMethod("POST"); // 请求方式
				conn.setRequestProperty("Charset", CHARSET); // 设置编码
				conn.setRequestProperty("connection", "keep-alive");
				conn.setRequestProperty("Content-Type", CONTENT_TYPE
						+ ";boundary=" + BOUNDARY);// 内容类型
				if (file != null) {
					/**
					 * 当文件不为空，把文件包装并且上传
					 */
					outputSteam = conn.getOutputStream();
					dos = new DataOutputStream(outputSteam);
					StringBuffer sb = new StringBuffer();
					sb.append(PREFIX);
					sb.append(BOUNDARY);// 边界标识 随机生成
					sb.append(LINE_END);
					/**
					 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
					 * filename是文件的名字，包含后缀名的 比如:abc.png
					 */
					sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
							+ file.getName() + "\"" + LINE_END);
					sb.append("Content-Type: application/octet-stream; charset="
							+ CHARSET + LINE_END);
					sb.append(LINE_END);
					//sb.append("img123=");
					dos.write(sb.toString().getBytes());
					InputStream is = new FileInputStream(file);
					byte[] bytes = new byte[1024];
					int len = 0;
					while ((len = is.read(bytes)) != -1) {
						dos.write(bytes, 0, len);
						if(len!=1024){
							System.out.println("len--"+len);
						}
					}
					
					is.close();
					//System.out.println("LINE_END为\r\n的长度--"+LINE_END.getBytes().length);
					//System.out.println("img=的长度为"+"img=".getBytes().length);
					
					dos.write(LINE_END.getBytes());
					//byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
					byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)		
							.getBytes();
					dos.write(end_data);
					//dos.flush();
					dos.close();
					outputSteam.close();
					
					/**
					 * 获取响应码 200=成功 当响应成功，获取响应的流
					 */
					int res = conn.getResponseCode();
					System.out.println(res);
					if (res == 200) {
						return SUCCESS;
					}
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (dos != null) {
					try {
						dos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (outputSteam != null) {
					try {
						outputSteam.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return FAILURE;
		
		}
		
		/**
		 * android客户端
		 * 
		 * @param file
		 * @return
		 */
		public static String uploadFile3(File file) {
			String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
			String PREFIX = "--";// 行开始
			String LINE_END = "\r\n";// 行结束
			String CONTENT_TYPE = "multipart/form-data"; // 内容类型
			// String RequestURL =
			// "http://192.168.0.100:7080/YkyPhoneService/Uploadfile1";
			// String RequestURL =
			// "http://127.0.0.1:8080/EDAIMobile/user/modifySculpture";
			
			//本机测试
			String RequestURL = "http://127.0.0.1:8080/edaiMobile/user/modifySculpture?localize=cn&versionCode=2.0&userId=2731804&fileName=head.jpg&fileContentType=jpg";
			//String RequestURL = "http://192.16.10.188:8080/edaiMobile/user/modifySculpture?localize=cn&versionCode=2.0&userId=2731804&fileName=480480.png&fileContentType=jpg";
			//服务器测试
			//String RequestURL = "http://172.17.34.102:7006/edaiMobileSect/user/modifySculpture?f8o1atdvUt5smNu1N6J4CocgninM6EaLyNdaf+X1lQs2B4lvDnycisTP+mps5QSOvWLF4SIhJt91+ZuU7Egx2W1aKDazHui78VKJPNtHPmF0lP0IVNPvLg==";
			
			OutputStream outputSteam = null;
			DataOutputStream dos = null;
			try {
				URL url = new URL(RequestURL);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setReadTimeout(TIME_OUT); // 超时时间
				conn.setConnectTimeout(TIME_OUT); // 超时时间
				conn.setDoInput(true); // 允许输入流
				conn.setDoOutput(true); // 允许输出流
				conn.setUseCaches(false); // 不允许使用缓存
				conn.setRequestMethod("POST"); // 请求方式
				conn.setRequestProperty("Charset", CHARSET); // 设置编码
				conn.setRequestProperty("connection", "keep-alive");
				conn.setRequestProperty("Content-Type", CONTENT_TYPE
						+ ";boundary=" + BOUNDARY);// 内容类型
				if (file != null) {
					/**
					 * 当文件不为空，把文件包装并且上传
					 */
					outputSteam = conn.getOutputStream();

					dos = new DataOutputStream(outputSteam);
					StringBuffer sb = new StringBuffer();
					sb.append(PREFIX);
					sb.append(BOUNDARY);// 边界标识 随机生成
					sb.append(LINE_END);
					/**
					 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
					 * filename是文件的名字，包含后缀名的 比如:abc.png
					 */
					sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
							+ file.getName() + "\"" + LINE_END);
					sb.append("Content-Type: application/octet-stream; charset="
							+ CHARSET + LINE_END);
					sb.append(LINE_END);
					//sb.append("img123=");
					dos.write(sb.toString().getBytes());
					InputStream is = new FileInputStream(file);
					byte[] bytes = new byte[1024];
					int len = 0;
					while ((len = is.read(bytes)) != -1) {
						dos.write(bytes, 0, len);
						if(len!=1024){
							System.out.println("len--"+len);
						}
					}
					
					is.close();
					//System.out.println("LINE_END为\r\n的长度--"+LINE_END.getBytes().length);
					//System.out.println("img=的长度为"+"img=".getBytes().length);
					
					dos.write(LINE_END.getBytes());
					//byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
					byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)		
							.getBytes();
					dos.write(end_data);
					//dos.flush();
					dos.close();
					outputSteam.close();
					/**
					 * 获取响应码 200=成功 当响应成功，获取响应的流
					 */
					int res = conn.getResponseCode();
					System.out.println(res);
					//获取响应信息
					//String responseMessage = conn.getResponseMessage();
					//System.out.println("====================================");
					//System.out.println(responseMessage);
					
					if (res == 200) {
						return SUCCESS;
					}
					
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (dos != null) {
					try {
						dos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (outputSteam != null) {
					try {
						outputSteam.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return FAILURE;
		
		}
		
		
	}

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		File f1 = new File("D:\\480480.png");
		//HttpAssist.uploadFile(f1);
		//HttpAssist.uploadFile2(f1);
		HttpAssist.uploadFile3(f1);
	}

}
